<template>
  <!-- 枚举-下拉框查询 -->
  <div>
    <a-select v-if="!isGroup" v-model="currentValue" v-bind="$attrs" :placeholder="placeholder" allow-clear
      v-on="$listeners" @change="handleChange">
      <a-icon v-if="fetching" slot="suffixIcon" style="color: #096dd9" type="loading" />
      <a-spin v-if="fetching" slot="notFoundContent" size="small" />

      <a-select-option v-for="i in list" :key="i[valueName]" :value="i[[valueName]]"
        :disabled="i.enabled === false && !isSearchPage">
        {{ i[labelName] }}
      </a-select-option>
    </a-select>
    <!-- 分类下拉选择 -->
    <a-select v-else v-model="currentValue" v-bind="$attrs" :placeholder="placeholder" allow-clear v-on="$listeners">
      <a-icon v-if="fetching" slot="suffixIcon" style="color: #096dd9" type="loading" />
      <a-spin v-if="fetching" slot="notFoundContent" size="small" />
      <a-select-opt-group v-for="i in list" :key="i[valueName]">
        <span slot="label">
          <a-icon type="user" />{{ i[labelName] }}
        </span>
        <a-select-option v-for="item in i.children" :key="item[valueName]" :value="item[[valueName]]">
          {{ item[labelName] }}
        </a-select-option>
      </a-select-opt-group>
    </a-select>
  </div>
</template>
<script>
import Api from '@/api/legal/branchContract/totalPackageContract.js'

export default {
  name: 'Selector',
  props: {
    // v-model绑定的数据
    value: {
      type: [Array, String, Object, Number]
    },
    // 0：检查类型 ,1：公司级别,2：检查结果,3：问题状态,4：整改结果
    selectType: {
      type: [String, Number],
      default: function () {
        return '0'
      }
    },
    jobLevel: {
      type: String
    },
    attr: {
      type: [Object]
    },
    form: {
      type: [Object]
    },
    formList: {
      type: Array
    },
    // placeholder
    placeholder: {
      type: String,
      default: function () {
        return '请选择'
      }
    },
    // value值名
    valueName: {
      type: String,
      default: function () {
        return 'id'
      }
    },
    labelName: {
      type: String,
      default: function () {
        return 'name'
      }
    },
    formColData: {
      type: Object
    },
    isDefault: {
      type: Boolean,
      default: false
    },
    isDefaultTypeId:{
      type: Boolean,
      default: false
    },
    isGroup: {
      type: Boolean,
      default: false
    },
    //自定义接口后缀URL
    apiSuffix: {
      type: String,
      default: () => 'queryTypesLabelList'
    },
    urlType: {
      type: String,
      default: () => 'quality'
    },
    // 过滤函数，当该属性有值时，按该函数进行结果过滤
    filterFn: {
      type: [Function],
      default: null
    },
    // 自定义查询参数
    customQuery: {
      type: Object,
      default() {
        return {}
      }
    },
    // 自定义查询参数
    customQueryType: {
      type: Object,
      default() {
        return {}
      }
    },
    // 自定义查询参数
    isEmpty: {
      type: Boolean,
      default: false
    },
    // 自定义请求API
    customApi: {
      type: [Object, Function],
      default: () => null
    },
    // 请求的数据层级。默认为res下的data
    dataValue: {
      type: String,
      default: () => 'data'
    },
    isSearchPage: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      fetching: false,
      list: []
    }
  },
  watch: {
    'customQueryType.query.type'(val, oldVal) {
      if (this.isEmpty && oldVal) {
        this.currentValue = []
      }
      if (val) {
        this.handleDate()
      }
    },
    'customQuery.searchQuery': {
      handler(val, oldVal) {
        if(val && oldVal && oldVal?.projectSet?.length && oldVal?.projectSet?.length && val.projectSet[0] !== oldVal.projectSet[0]){
         this.handleDate()
        }
      },
    },
    jobLevel(val, oldVal){
      this.handleDate()
    },
    form: {
      handler: function (val, oldVal) {
        if(this.isDefaultTypeId){
           if(!val?.typeId){
             if(this.list.length>0) {
               this.$emit('input', this.list[0][this.valueName])
               this.$emit('change', this.list[0][this.valueName])
             }
           }
        }
        //如果有定义viewName的情况下
        if (this.formColData && this.formColData.viewName) {
          this.setSelVal();
        }
      },
      deep: true,
    }
  },
  computed: {
    // 转换绑定的选中数据，与v-model同步
    currentValue: {
      get: function () {
        if (this.list.length > 0) {
          this.$emit(
            'update:option',
            this.list?.find((item) => item.id === this.value)
          )
          this.$emit(
            'getOption',
            this.list.find((item) => item.id === this.value)
          )
        }
        return this.value
      },
      set: function (value) {
        this.$emit('input', value)
      }
    }
  },
  methods: {
    handleChange(val, vm) {
      const item = this.list.find((ele)=>ele[this.valueName] === val)
      this.$emit('change', val, vm)
      this.$emit('onChange', item)
    },
    handleDate() {
      // 获取下拉框列表
      this.fetching = true
      let args = { type: this.selectType }
      if (this.attr && Object.keys(this.attr)?.length > 0) {
        Object.assign(args, this.attr)
      }
      let api
      // 质量
      if (!this.customApi) {
        if (this.urlType === 'quality') {
          const { typesLabel } = require('@/api/quality/quality')
          api = typesLabel
          // 工程
        } else if (this.urlType === 'project') {
          const { getLabel } = require('@/api/project/projects')
          api = { getList: getLabel }
          // 办公
        } else if (this.urlType === 'office') {
          const { enterpriseHonor } = require('@/api/office/office/enterpriseHonorAndImgCollect')
          api = { getList: enterpriseHonor.getLabels }
          args = { query: args }
          // 工会
        } else if (this.urlType === 'union') {
          const { unionApiUrl } = require('@/api/config.js')
          const Union = require('@/api/union').default
          const { getLabels } = new Union(unionApiUrl, this.apiSuffix)
          api = { getList: getLabels }
        } else if (this.urlType === 'legal') {
          const { getDropDown } = require('@/api/legal.js')
          api = { getList: getDropDown }
          args = this.customQuery
        } else if (this.urlType === 'legalChange') {
          const { getLabels } = require('@/api/legal/change/index.js')
          api = { getList: getLabels }
          args = this.customQueryType
        } else if (this.urlType === 'commercial') {
          const { getLabels } = require('@/api/businessAffairs/common.js')
          api = { getList: getLabels }
        } else if (this.urlType === 'technical') {
          const { list } = require('@/api/technical/config')
          api = { getList: list }
        }
      } else {
        api = { getList: this.customApi }
        args = this.customQuery
      }
      api
        .getList(args)
        .then((res) => {
          this.fetching = false
          let newData = [];
          const dataList = eval('res.' + this.dataValue) || [];
          //根据选中的受检单位对检查类别下拉数据进行过滤
          if (this.jobLevel && this.jobLevel != 'PD') {
            //受检单位不为项目部时，则检查类别为管理行为和工程资料；
            dataList.forEach((v) => {
              if (v.code === '2' || v.code === '3'){
                newData.push(v)
              }
            })
          }else{
            newData = dataList;
          }
          if (this.filterFn) {
            this.list = newData.filter(this.filterFn)
          } else {
            this.list = newData
          }
          //如果有定义viewName的情况下
          if (this.formColData && this.formColData.viewName) {
            this.setSelVal();
          }
          if (this.isDefault) {
            this.$emit('input', this.list[0][this.valueName])
            this.$emit('change', this.list[0][this.valueName])
            this.$emit('onChange', this.list[0])
          }
          this.$emit('update:list', this.list)
          this.$emit('getList', this.list)
        })
        .catch((res) => {
          this.fetching = false
        })
    },
    //code未匹配到对应的label值时，展示历史数据label值
    setSelVal() {
      if (!this.form[this.formColData.keyName] || this.form[this.formColData.keyName].length === 0) {
        this.currentValue = void 0;
      } else {
        let _obj = this.list.find((v) => v[this.formColData.keyName] === this.form[this.formColData.keyName])
        if (!_obj) {
          this.currentValue = this.form[this.formColData.viewName] ? this.form[this.formColData.viewName] : this.form[this.formColData.keyName];
        } else {
          this.currentValue = this.form[this.formColData.keyName];
        }
      }
    }
  },
  mounted() {
    this.handleDate()
  }
}
</script>
